package com.gitee.zw.irmp.common.audit;

import com.gitee.zw.irmp.common.auth.AuthUtils;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.auditing.DateTimeProvider;
import org.springframework.data.domain.AuditorAware;
import org.springframework.data.jpa.repository.config.EnableJpaAuditing;
import org.springframework.stereotype.Component;

import java.time.ZonedDateTime;
import java.time.temporal.TemporalAccessor;
import java.util.Optional;

@Configuration
@EnableJpaAuditing(auditorAwareRef = "IrmpAuditorAware", dateTimeProviderRef = "zonedDateTimeProvider")
public class AuditorAwareConfig {

    @Bean("IrmpAuditorAware")
    AuditorAware<String> create() {
        return () -> Optional.ofNullable(AuthUtils.getLoginUsername());
    }

    @Component("zonedDateTimeProvider")
    public class CustomDateTimeProvider implements DateTimeProvider {

        @Override
        public Optional<TemporalAccessor> getNow() {
            return Optional.of(ZonedDateTime.now());
        }
    }
}
